/**
 * created by dqn 2018/3/17 10:39
 */

package main.service.impl;

import main.entity.SongCollect;
import main.repository.SongCollectRepository;
import main.service.SongCollectService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;

@Service
public class SongCollectServiceImpl implements SongCollectService {
    @Autowired
    SongCollectRepository songCollectRepository;
    @Override
    public List<SongCollect> getSongCollectsByUserId(int id) {
        return songCollectRepository.getSongCollectsByUserId(id).orElse(new ArrayList<>());
    }

    @Override
    public SongCollect likeSong(int user, int song) {
        Optional<SongCollect> songCollectOptional = songCollectRepository.getSongCollectBySongIdAndUserId(song,user);
        if (songCollectOptional.isPresent()){
            return songCollectOptional.get();
        }
        SongCollect songCollect = new SongCollect();
        songCollect.setSongId(song);
        songCollect.setUserId(user);
        System.out.println("inserting..."+songCollect.toString());
        return songCollectRepository.save(songCollect);
    }

    @Override
    public boolean dislikeSong(int user, int song) {
        Optional<SongCollect> songCollectOptional = songCollectRepository.getSongCollectBySongIdAndUserId(song,user);
        if (!songCollectOptional.isPresent()){
            return true;
        }
        try {
            songCollectRepository.delete(songCollectOptional.get());
        }catch (Exception e){
            return false;
        }
        return true;
    }

    @Override
    public boolean isLike(int user, int song) {
        return songCollectRepository.getSongCollectBySongIdAndUserId(song,user).isPresent();
    }

    @Override
    public boolean deleteBySongId(int id) {
        try {
            songCollectRepository.deleteSongCollectsBySongId(id);
        }catch (Exception e){
            return false;
        }
        return true;
    }
}
